package jehc.cloud.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jehc.cloud.common.base.BaseResult;
import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @Desc 加解密工具类
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Slf4j
public class DecryptUtils {

    public static final String AESKey = "jehcEncryAESKeys";

    public static final String signKey = "jehcEncrySignKeys";

    /**
     * 加密
     * @param value
     * @return
     * @throws Exception
     */
    public static String encrypt(String value) throws Exception {
        if (StringUtil.isEmpty(AESKey)) {
            log.error("Key为空null");
            return null;
        }
        byte[] raw = AESKey.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(value.getBytes("utf-8"));
        return Base64.getEncoder().encodeToString(encrypted);//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    }


    /**
     * 加密
     * @param key
     * @param value
     * @return
     * @throws Exception
     */
    public static BaseResult<String> encrypt(String key,String value) throws Exception {
        if (StringUtil.isEmpty(key)) {
            log.error("Key为空null");
            return null;
        }
        byte[] raw = key.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] encrypted = cipher.doFinal(value.getBytes("utf-8"));
        return BaseResult.success(Base64.getEncoder().encodeToString(encrypted));//此处使用BASE64做转码功能，同时能起到2次加密的作用。
    }

    /**
     * 解密
     * @param value
     * @return
     * @throws Exception
     */
    public static BaseResult<String> decrypt(String value){
        try {
            byte[] raw = AESKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = Base64.getDecoder().decode(value);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original, "utf-8");
                return BaseResult.success(originalString);
            } catch (Exception e) {
                log.error("解密失败：{}",e.toString());
                return BaseResult.fail();
            }
        } catch (Exception ex) {
            log.error("解密失败：{}",ex.toString());
            return BaseResult.fail();
        }
    }

    /**
     * 解密
     * @param key
     * @param value
     * @return
     * @throws Exception
     */
    public static BaseResult<String> decrypt(String key,String value) {
        try {
            if (StringUtil.isEmpty(key)) {
                log.error("Key为空null");
                return null;
            }
            byte[] raw = key.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            byte[] encrypted1 = Base64.getDecoder().decode(value);//先用base64解密
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original, "utf-8");
                return BaseResult.success(originalString);
            } catch (Exception e) {
                log.error("解密失败：{}",e.toString());
                return BaseResult.fail();
            }
        } catch (Exception ex) {
            log.error("解密失败：{}",ex.toString());
            return BaseResult.fail();
        }
    }

    /**
     * AES解密 加MD5签名验证。
     * @param requestBytes
     * @return
     */
    public static byte[] decrypt(byte[] requestBytes){
        if (requestBytes.length <= 0) {
            return new byte[0];
        }
        String requestData = new String(requestBytes, StandardCharsets.UTF_8);
        JSONObject jsonobj = JSON.parseObject(requestData);

        log.info("收到的加密数据：" + jsonobj);
        String encrypt = jsonobj.get("encrypt") == null ? "" : jsonobj.get("encrypt").toString();
        String decrypt = "";
        if (encrypt.length() > 0) {
            //解密参数
            BaseResult baseResult = DecryptUtils.decrypt(encrypt, AESKey);
            decrypt = ""+baseResult.getData();
            if (StringUtil.isEmpty(decrypt)) {
                //解密失败，返回异常
                throw new ExceptionUtil("解密失败");
            }
        }
        log.info("解密后的数据：" + decrypt);
        //获取并验证签名。
        String sign = jsonobj.get("sign") == null ? "" : jsonobj.get("sign").toString();
        String md5Data = MD5.md5(decrypt + signKey);
        if (!sign.equals(md5Data)) {
            //验签失败
            throw new ExceptionUtil("验证签名失败");
        }
        //验证通过，返回解密后的参数
        return decrypt.getBytes(StandardCharsets.UTF_8);
    }

    /**
     * AES加密 加MD5签名验证。
     * @param requestBytes
     * @return
     */
    public byte[] encrypt(byte[] requestBytes) throws Exception {
        if (requestBytes.length <= 0) {
            return new byte[0];
        }
        String requestData = new String(requestBytes, StandardCharsets.UTF_8);
        String encrypt = "";
        if (requestData.length() > 0) {
            //加密密文
            BaseResult baseResult =DecryptUtils.decrypt(requestData, AESKey);
            encrypt = ""+baseResult.getData();
            if (StringUtil.isEmpty(encrypt)) {
                //加密失败，返回异常
                throw new ExceptionUtil("加密失败");
            }
        }
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("encrypt", encrypt);//加密数据
        jsonObj.put("sign", MD5.md5(requestData + signKey));//签名
        log.info("加密签名后数据：" + jsonObj);
        //验证通过，返回解密后的参数
        return jsonObj.toJSONString().getBytes(StandardCharsets.UTF_8);
    }
}
